/**
 * 交易分析页面JS
 */
$(document).ready(function() {
    // 初始化日期选择器
    $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        language: 'zh-CN'
    });
    
    // 日期范围选择变化事件
    $('#dateRange').change(function() {
        if ($(this).val() === 'custom') {
            $('#startDate, #endDate').prop('disabled', false);
        } else {
            $('#startDate, #endDate').prop('disabled', true);
            
            // 根据选择的日期范围设置开始和结束日期
            var today = new Date();
            var endDate = formatDate(today);
            var startDate = '';
            
            var days = parseInt($(this).val());
            if (!isNaN(days)) {
                var startDateObj = new Date();
                startDateObj.setDate(today.getDate() - days);
                startDate = formatDate(startDateObj);
            }
            
            // 更新统计数据
            loadStatistics(startDate, endDate);
        }
    });
    
    // 分析按钮点击事件
    $('#analyzeBtn').click(function() {
        var dateRange = $('#dateRange').val();
        var startDate = '';
        var endDate = '';
        
        if (dateRange === 'custom') {
            startDate = $('#startDate').val();
            endDate = $('#endDate').val();
            
            if (!startDate || !endDate) {
                alert('请选择开始和结束日期');
                return;
            }
        } else {
            var today = new Date();
            endDate = formatDate(today);
            
            var days = parseInt(dateRange);
            if (!isNaN(days)) {
                var startDateObj = new Date();
                startDateObj.setDate(today.getDate() - days);
                startDate = formatDate(startDateObj);
            }
        }
        
        // 加载统计数据
        loadStatistics(startDate, endDate);
    });
    
    // 初始加载30天数据
    var today = new Date();
    var endDate = formatDate(today);
    var startDateObj = new Date();
    startDateObj.setDate(today.getDate() - 30);
    var startDate = formatDate(startDateObj);
    
    // 加载统计数据
    loadStatistics(startDate, endDate);
    
    // 窗口大小变化时重新调整图表大小
    $(window).resize(function() {
        resizeAllCharts();
    });
});

// 格式化日期为yyyy-MM-dd
function formatDate(date) {
    var year = date.getFullYear();
    var month = (date.getMonth() + 1).toString().padStart(2, '0');
    var day = date.getDate().toString().padStart(2, '0');
    return year + '-' + month + '-' + day;
}

// 加载统计数据
function loadStatistics(startDate, endDate) {
    // 显示加载中状态
    showLoading();
    
    // 发送AJAX请求获取统计数据
    $.ajax({
        url: '/api/transaction/statistics',
        type: 'GET',
        data: {
            startDate: startDate,
            endDate: endDate
        },
        success: function(res) {
            if (res.code === 200) {
                // 更新统计卡片
                updateStatCards(res.data);
                
                // 更新图表
                updateCharts(res.data);
                
                // 隐藏加载中状态
                hideLoading();
            } else {
                alert('加载统计数据失败：' + res.message);
                hideLoading();
            }
        },
        error: function(xhr) {
            alert('加载统计数据失败：' + xhr.statusText);
            hideLoading();
            
            // 使用模拟数据进行展示
            useMockData();
        }
    });
}

// 显示加载中状态
function showLoading() {
    $('#totalTransactions').html('<i class="fas fa-spinner fa-spin"></i>');
    $('#totalAmount').html('<i class="fas fa-spinner fa-spin"></i>');
    $('#avgDailyTransactions').html('<i class="fas fa-spinner fa-spin"></i>');
    $('#growthRate').html('<i class="fas fa-spinner fa-spin"></i>');
}

// 隐藏加载中状态
function hideLoading() {
    // 已在updateStatCards中更新了内容，此处无需操作
}

// 更新统计卡片
function updateStatCards(data) {
    $('#totalTransactions').text(data.totalTransactions.toLocaleString());
    $('#totalAmount').text('¥' + data.totalAmount.toLocaleString());
    $('#avgDailyTransactions').text(data.avgDailyTransactions.toFixed(1));
    
    var growthRate = data.growthRate;
    var growthRateText = (growthRate > 0 ? '+' : '') + growthRate.toFixed(1) + '%';
    var growthRateClass = growthRate >= 0 ? 'text-success' : 'text-danger';
    
    $('#growthRate').text(growthRateText).removeClass('text-success text-danger').addClass(growthRateClass);
}

// 更新图表
function updateCharts(data) {
    // 交易趋势图
    updateTransactionTrendChart(data.transactionTrend);
    
    // 交易类型分布图
    updateTransactionTypeChart(data.transactionTypeDistribution);
    
    // 产品交易TOP10图
    updateProductTopChart(data.productTopList);
    
    // 仓库交易分布图
    updateWarehouseDistributionChart(data.warehouseDistribution);
    
    // 月度交易对比图
    updateMonthlyComparisonChart(data.monthlyComparison);
}

// 更新交易趋势图
function updateTransactionTrendChart(trendData) {
    var trendChart = echarts.init(document.getElementById('transactionTrendChart'));
    
    var dates = trendData.map(function(item) {
        return item.date;
    });
    
    var counts = trendData.map(function(item) {
        return item.count;
    });
    
    var amounts = trendData.map(function(item) {
        return (item.amount / 10000).toFixed(2); // 转换为万元
    });
    
    var option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985'
                }
            }
        },
        legend: {
            data: ['交易数量', '交易金额(万元)']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: dates
        },
        yAxis: [
            {
                type: 'value',
                name: '交易数量'
            },
            {
                type: 'value',
                name: '交易金额(万元)',
                axisLabel: {
                    formatter: '{value} 万元'
                }
            }
        ],
        series: [
            {
                name: '交易数量',
                type: 'line',
                data: counts
            },
            {
                name: '交易金额(万元)',
                type: 'line',
                yAxisIndex: 1,
                data: amounts
            }
        ]
    };
    
    trendChart.setOption(option);
}

// 更新交易类型分布图
function updateTransactionTypeChart(typeData) {
    var typeChart = echarts.init(document.getElementById('transactionTypeChart'));
    
    var data = [];
    for (var type in typeData) {
        if (typeData.hasOwnProperty(type)) {
            var typeName = getTransactionTypeName(type);
            data.push({
                name: typeName,
                value: typeData[type]
            });
        }
    }
    
    var option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 10,
            data: data.map(function(item) {
                return item.name;
            })
        },
        series: [
            {
                name: '交易类型',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '18',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: data
            }
        ]
    };
    
    typeChart.setOption(option);
}

// 更新产品交易TOP10图
function updateProductTopChart(productData) {
    var productChart = echarts.init(document.getElementById('productTopChart'));
    
    var products = productData.map(function(item) {
        return item.productName;
    });
    
    var counts = productData.map(function(item) {
        return item.count;
    });
    
    var amounts = productData.map(function(item) {
        return (item.amount / 10000).toFixed(2); // 转换为万元
    });
    
    var option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: ['交易数量', '交易金额(万元)']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value'
        },
        yAxis: {
            type: 'category',
            data: products
        },
        series: [
            {
                name: '交易数量',
                type: 'bar',
                data: counts
            },
            {
                name: '交易金额(万元)',
                type: 'bar',
                data: amounts
            }
        ]
    };
    
    productChart.setOption(option);
}

// 更新仓库交易分布图
function updateWarehouseDistributionChart(warehouseData) {
    var warehouseChart = echarts.init(document.getElementById('warehouseDistributionChart'));
    
    var data = [];
    for (var warehouse in warehouseData) {
        if (warehouseData.hasOwnProperty(warehouse)) {
            data.push({
                name: warehouse,
                value: warehouseData[warehouse]
            });
        }
    }
    
    var option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 10,
            data: data.map(function(item) {
                return item.name;
            })
        },
        series: [
            {
                name: '仓库交易',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: data,
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    
    warehouseChart.setOption(option);
}

// 更新月度交易对比图
function updateMonthlyComparisonChart(monthlyData) {
    var monthlyChart = echarts.init(document.getElementById('monthlyComparisonChart'));
    
    var months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    
    var currentYearData = Array(12).fill(0);
    var previousYearData = Array(12).fill(0);
    
    var currentYear = new Date().getFullYear();
    var previousYear = currentYear - 1;
    
    // 填充数据
    for (var i = 0; i < monthlyData.length; i++) {
        var item = monthlyData[i];
        var year = parseInt(item.yearMonth.substring(0, 4));
        var month = parseInt(item.yearMonth.substring(5, 7)) - 1;
        
        if (year === currentYear) {
            currentYearData[month] = item.count;
        } else if (year === previousYear) {
            previousYearData[month] = item.count;
        }
    }
    
    var option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: [previousYear + '年', currentYear + '年']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                data: months
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: previousYear + '年',
                type: 'bar',
                data: previousYearData
            },
            {
                name: currentYear + '年',
                type: 'bar',
                data: currentYearData
            }
        ]
    };
    
    monthlyChart.setOption(option);
}

// 获取交易类型名称
function getTransactionTypeName(type) {
    var typeMap = {
        'IN': '采购入库',
        'OUT': '销售出库',
        'TRANSFER': '库存调拨',
        'CHECK': '库存盘点'
    };
    return typeMap[type] || type;
}

// 重新调整所有图表大小
function resizeAllCharts() {
    if (document.getElementById('transactionTrendChart')) {
        echarts.getInstanceByDom(document.getElementById('transactionTrendChart')).resize();
    }
    if (document.getElementById('transactionTypeChart')) {
        echarts.getInstanceByDom(document.getElementById('transactionTypeChart')).resize();
    }
    if (document.getElementById('productTopChart')) {
        echarts.getInstanceByDom(document.getElementById('productTopChart')).resize();
    }
    if (document.getElementById('warehouseDistributionChart')) {
        echarts.getInstanceByDom(document.getElementById('warehouseDistributionChart')).resize();
    }
    if (document.getElementById('monthlyComparisonChart')) {
        echarts.getInstanceByDom(document.getElementById('monthlyComparisonChart')).resize();
    }
}

// 使用模拟数据
function useMockData() {
    var mockData = {
        totalTransactions: 1284,
        totalAmount: 1256890,
        avgDailyTransactions: 42.8,
        growthRate: 12.5,
        transactionTrend: [
            {date: '2023-01-01', count: 120, amount: 220000},
            {date: '2023-02-01', count: 132, amount: 180000},
            {date: '2023-03-01', count: 101, amount: 190000},
            {date: '2023-04-01', count: 134, amount: 230000},
            {date: '2023-05-01', count: 90, amount: 290000},
            {date: '2023-06-01', count: 230, amount: 330000},
            {date: '2023-07-01', count: 210, amount: 310000},
            {date: '2023-08-01', count: 182, amount: 400000},
            {date: '2023-09-01', count: 191, amount: 380000},
            {date: '2023-10-01', count: 234, amount: 420000},
            {date: '2023-11-01', count: 290, amount: 500000},
            {date: '2023-12-01', count: 330, amount: 580000}
        ],
        transactionTypeDistribution: {
            'IN': 335,
            'OUT': 310,
            'TRANSFER': 234,
            'CHECK': 135
        },
        productTopList: [
            {productName: '大米', count: 320, amount: 1200000},
            {productName: '小麦', count: 302, amount: 1020000},
            {productName: '玉米', count: 301, amount: 1010000},
            {productName: '高粱', count: 334, amount: 1340000},
            {productName: '大豆', count: 390, amount: 1900000},
            {productName: '花生', count: 330, amount: 1300000},
            {productName: '土豆', count: 320, amount: 1200000},
            {productName: '红薯', count: 301, amount: 1010000},
            {productName: '白菜', count: 334, amount: 1340000},
            {productName: '萝卜', count: 390, amount: 1900000}
        ],
        warehouseDistribution: {
            '1号仓': 335,
            '2号仓': 310,
            '3号仓': 234,
            '4号仓': 135,
            '5号仓': 1548
        },
        monthlyComparison: [
            {yearMonth: '2022-01', count: 120},
            {yearMonth: '2022-02', count: 132},
            {yearMonth: '2022-03', count: 101},
            {yearMonth: '2022-04', count: 134},
            {yearMonth: '2022-05', count: 90},
            {yearMonth: '2022-06', count: 230},
            {yearMonth: '2022-07', count: 210},
            {yearMonth: '2022-08', count: 182},
            {yearMonth: '2022-09', count: 191},
            {yearMonth: '2022-10', count: 234},
            {yearMonth: '2022-11', count: 290},
            {yearMonth: '2022-12', count: 330},
            {yearMonth: '2023-01', count: 220},
            {yearMonth: '2023-02', count: 182},
            {yearMonth: '2023-03', count: 191},
            {yearMonth: '2023-04', count: 234},
            {yearMonth: '2023-05', count: 290},
            {yearMonth: '2023-06', count: 330},
            {yearMonth: '2023-07', count: 310},
            {yearMonth: '2023-08', count: 123},
            {yearMonth: '2023-09', count: 442},
            {yearMonth: '2023-10', count: 321},
            {yearMonth: '2023-11', count: 90},
            {yearMonth: '2023-12', count: 149}
        ]
    };
    
    // 更新统计卡片
    updateStatCards(mockData);
    
    // 更新图表
    updateCharts(mockData);
} 